
import { useCrudForm } from "@/composables/useCrudForm";
import { dismissRequestFormConfig } from "../form-config";
import { formatDateTime } from "@/utils/xenUtils";
import SysHrDismissRequestBillApi from "../api/index";
import commonApi from "@/api/common";
import type {
  ISysHrDismissRequestBill,
  ISysHrDismissRequestBillVm,
} from "../api/interface";

/**
 * 开除申请信息专用 Composable
 */
export function useDismissRequestInfo() {
  // 创建API实例
  const api = SysHrDismissRequestBillApi();

  // API配置
  const apiConfig = {
    search: api.search,
    get: api.get,
    add: api.add,
    edit: api.edit,
    delete: api.delete,
  };

  // 选项数据加载器
  const optionLoaders = {
    group: async () => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetParentsTree();
      // 转换为useCrudForm期望的格式
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text,
      }));
    },
  };

  // 使用通用CRUD表单
  const crudForm = useCrudForm<ISysHrDismissRequestBill, ISysHrDismissRequestBillVm>(
    dismissRequestFormConfig,
    apiConfig,
    optionLoaders
  );

  /**
   * 字段映射配置（API字段路径到表单字段的映射）
   */
  const fieldMapping = {
    // 单据信息
    billCode: "BillCode",
    billStatus: "BillStatus",
    workflowStatus: "WorkflowStatus",
    remark: "Remark",

    // 开除信息
    personName: "Name", // 员工姓名
    staffNo: "StaffNo", // 员工工号
    dismissDate: "DismissDate",
    resignType: "ResignType",
    describe: "Describe",

    // 流程信息
    approver: "Approver",
    approvalTime: "ApprovalTime",

    // 工作信息
    group: "Group.GroupName", // 直接映射到部门名称


  };

  /**
   * 加载开除申请详情数据
   */
  const loadDismissRequestDetail = async (id: string): Promise<{ success: boolean; isMyApprove?: boolean }> => {
    try {
      // 直接调用API获取完整响应
      const response = await api.get(id);

      if (response && response.Entity) {
        const detail = response.Entity;

        // 设置原始数据
        crudForm.originalData.value = detail;

        // 检查原始数据中的日期字段
        const dateFields = ["ApprovalTime", "DismissDate"];
        dateFields.forEach(field => {
          if ((detail as any)[field]) {
            console.log(`原始数据中的日期字段 ${field}:`, (detail as any)[field]);
          }
        });

        // 先使用通用转换
        crudForm.convertApiDataToFormData(detail, fieldMapping);

        // 添加特殊处理，确保选择器字段正确映射
        await ensurePickerFieldsMapping(detail);

        return {
          success: true,
          isMyApprove: response.IsMyApprove || false
        };
      }
      return { success: false };
    } catch (error) {
      console.error("获取开除申请详情失败:", error);
      return { success: false };
    }
  };

  /**
   * 确保选择器字段正确映射
   */
  const ensurePickerFieldsMapping = async (apiData: any) => {
    // 处理部门
    if (apiData.GroupId && dismissRequestFormConfig.group?.optionsData) {
      const groupOption = dismissRequestFormConfig.group.optionsData.find(
        (item: any) => item.value === apiData.GroupId
      );
      if (groupOption) {
        crudForm.formData.group = groupOption.text;
        crudForm.pickerValues.group = groupOption.value;
      }
    }

    // 处理单据状态显示
    if (apiData.BillStatus !== undefined) {
      crudForm.formData.billStatus = apiData.BillStatus || "";
    }

    // 处理状态显示
    if (apiData.WorkflowStatus !== undefined) {
      crudForm.formData.workflowStatus = apiData.WorkflowStatus || "";
    }

    // 处理辞退类型显示
    if (apiData.ResignType !== undefined) {
      crudForm.formData.resignType = apiData.ResignType || "";
    }

    // 处理审批时间格式化
    if (apiData.ApprovalTime) {
      crudForm.formData.approvalTime = formatDateTime(apiData.ApprovalTime);
    }

    // 处理开除日期格式化
    if (apiData.DismissDate) {
      const formattedDateTime = formatDateTime(apiData.DismissDate);
      crudForm.formData.dismissDate = formattedDateTime ? formattedDateTime.split(' ')[0] : '';
    }
  };

  return {
    // 继承通用CRUD表单的所有功能
    ...crudForm,

    // 开除申请信息专用方法
    loadDismissRequestDetail,

    // 字段映射
    fieldMapping,
  };
}
